<script setup>
import { ref, onMounted, onUnmounted  } from 'vue'
import ASRRecorder from "@/utils/ASR/ASRRecorder.js"
let asrRecorder


// 引用DOM元素
const resultTextRef = ref(null)

// 状态变量
const statusText = ref('准备就绪')
const audioContext = ref(null)
const stream = ref(null)
const isRecording = ref(false)

const result = (resultData) =>{
  
}

// 开始录音
const startAsr = async () => {
  if (!asrRecorder) return
  try {
    statusText.value = '正在初始化...'
    // 启用语音识别功能
    // asrRecorder.setEnabled(true)
    // 开始录音识别
    await asrRecorder.start()

    isRecording.value = true
    statusText.value = '正在录音识别...'
  } catch (error) {
    console.error('开始录音识别失败:', error)
    statusText.value = '开始录音识别失败: ' + error.message
  }
}


// 停止录音
const stopAsr = async () => {
  if (!asrRecorder) return

  asrRecorder.stop()
  isRecording.value = false
  statusText.value = '录音已停止'
}

// 键盘事件处理
const handleKeydown = (event) => {
  if (event.code === "Space" && !isRecording.value) {
    startAsr()
    window.removeEventListener("keydown", handleKeydown)
  }    
}

const handleKeyup = (event) => {
  if (event.code === "Space" && isRecording.value){
    stopAsr()
    window.addEventListener("keydown", handleKeydown)
  }
}
const getCookie = (name) => {
    const cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
      const cookie = cookies[i].trim();
      if (cookie.startsWith(name + '=')) {
        return cookie;
      }
    }
    return '';
  };
// 组件挂载时初始化
onMounted(() => {
  document.cookie="QTK=cb191381-5d58-4993-9c6d-08bc547c0276"
  let qtk = getCookie("QTK")
  // asrRecorder = new ASRRecorder({wsUrl:`ws://192.168.5.200:8082/qiwei/asr/websocket?${qtk}`})
  asrRecorder = new ASRRecorder({wsUrl:`wss://static.dhljai.com/api/asr/websocket?${qtk}`})
  // 设置回调函数
  asrRecorder.onTextChange =(data) => {
    console.log('识别结果:', data)
    let content = JSON.parse(data);
    if(content.c === "100"){
      if(content.d === ""){
        alert("识别结果为空")
      }else{
        resultTextRef.value.innerText = content.d
      }
    }else{
      alert("识别出错")
    }
  }

  // 添加键盘事件监听
  window.addEventListener("keydown", handleKeydown)
  window.addEventListener("keyup", handleKeyup)
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener("keydown", handleKeydown)
  window.removeEventListener("keyup", handleKeyup)
  
})
const playAudio = () => {
}
</script>

<template>
  <div class="containerASR">
    <h1 class="title">语音识别</h1>
    <div class="fun_view">
      <div class="fun">
        <div class="controls">
          <button @click="startAsr" :disabled="isRecording">开始录音识别</button>
          <button @click="stopAsr" :disabled="!isRecording">停止录音停止</button>
        </div>
        <div class="status">
          <p id="statusText">{{ statusText }}</p>
        </div>
      </div>
    </div>
    
    <div class="result">
      <h2 class="text">识别结果：</h2>
      <div class="resultText" >
        <div ref="resultTextRef" contenteditable="true">
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.containerASR{
    width: 100%;
    height: 100%;
    margin: auto;
    background-color: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    user-select: none;
    .title{
        color: #333;
    }
    .fun_view{
        height: 120px;
        display: flex;
        .fun{
            flex: 1;
            .controls {
                display: flex;
                justify-content: center;
                margin: 20px 0;
                gap: 10px;
                button {
                    padding: 10px 20px;
                    font-size: 16px;
                    cursor: pointer;
                    background-color: #4CAF50;
                    color: white;
                    border: none;
                    border-radius: 4px;
                    transition: background-color 0.3s;
                    &:hover {
                        background-color: #45a049;
                    }
                    &:disabled {
                        background-color: #cccccc;
                        cursor: not-allowed;
                    }
                }
            }
            .status {
                text-align: center;
                margin: 10px 0;
                font-size: 16px;
                color: #666;
            }
        }
        .view{
            flex: 1;
            width: 100%;
            height: 100%;
            background: #f9f9f9;
            .canvas {
                width: 100%;
                height: 100%;
            }
        }
    }
   
    .result {
        height:  calc(100% - 180px);
        margin-top: 20px;
        padding: 15px;
        background-color: #f9f9f9;
        border-radius: 4px;
        border: 1px solid #ddd;
        flex: 1;
        display: flex;
        flex-direction: column;
        .text{
          margin-bottom: 10px;
        }
        .resultText{
            height:100% ;
            line-height: 1.5;
            padding: 10px;
            user-select: text;
            overflow-y: auto;     
            white-space: pre-wrap;
            word-break: break-word;
            box-sizing: border-box;
            overflow-y: auto;
        }
    }

}
</style>
